<?php

namespace App\Admin\Controllers;

use App\Admin\Filters\SystemMediaFilter;
use App\Admin\Requests\SystemMediaCategoryRequest;
use App\Admin\Requests\SystemMediaRequest;
use App\Admin\Resources\SystemMediaResource;
use App\Admin\Models\SystemMediaCategory;
use App\Admin\Models\Config;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SystemMediaCategoryController extends Controller
{
    public function __construct() {
        // 判断ID为1的默认分类是否存在，不存在则创建
        $systemMediaCategory = SystemMediaCategory::find(1);
        if (!$systemMediaCategory) {
            DB::statement("INSERT INTO system_media_categories (id, parent_id, name, created_at, updated_at) VALUES (1, 0, '默认', '".date('Y-m-d H:i:s')."', '".date('Y-m-d H:i:s')."')");
        }
    }

    /**
	* showdoc
	* @catalog 接口简介/全局相关
	* @title 文件上传
	* @description 文件上传的接口
	* @method POST
	* @url /admin-api/system-media-categories/{category_id}/system-media
    * @param category_id 是 int 分类ID，地址栏参数，固定传1
    * @param file 是 上传文件
	* @return {"origin_filename":"958fac2089caf53ede5497e4412554cd.jpeg","filename":"9ec2a7c169979cb8d7c78d16c505adcf.jpeg","ext":"jpeg","path":"\/uploads\/9ec2a7c169979cb8d7c78d16c505adcf.jpeg","path_key":"b7e240d9411d632238ba89c44b4e3736","size":188082,"mime_type":"image\/png","category_id":1,"updated_at":"2022-05-31 17:44:59","created_at":"2022-05-31 17:44:59","id":1,"location":"\/uploads\/9ec2a7c169979cb8d7c78d16c505adcf.jpeg"}
	* @return_param id int(10) 文件ID
    * @return_param origin_filename varchar(100) 原始文件名
    * @return_param filename varchar(100) 文件名
    * @return_param ext varchar(20) 文件后缀
    * @return_param category_id int(10) 分类ID
    * @return_param path varchar(255) 路径
    * @return_param path_key varchar(32) 加密key
    * @return_param size varchar(255) 单位
    * @return_param mime_type varchar(100) 类型
    * @return_param created_at timestamp 创建时间
    * @return_param updated_at timestamp 更新时间
    * @remark 这里是备注信息
	* @number 99
	*/
    public function store(SystemMediaCategoryRequest $request)
    {
        $inputs = $request->validated();
        $cate = SystemMediaCategory::create($inputs);
        return $this->created($cate);
    }

    public function update(
        SystemMediaCategoryRequest $request,
        SystemMediaCategory $systemMediaCategory
    ) {
        $inputs = $request->validated();
        $systemMediaCategory->update($inputs);
        return $this->created($systemMediaCategory);
    }

    public function edit(SystemMediaCategory $systemMediaCategory)
    {
        return $this->ok($systemMediaCategory);
    }

    public function destroy(SystemMediaCategory $systemMediaCategory)
    {
        $systemMediaCategory->delete();
        return $this->noContent();
    }

    public function index(Request $request, SystemMediaCategory $model)
    {
        return $this->ok($model->treeExcept((int) $request->input('except'))->toTree());
    }

    /**
     * 上传文件到指定分类下
     *
     * @param SystemMediaRequest $request
     * @param SystemMediaCategory $systemMediaCategory
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function storeSystemMedia(
        SystemMediaRequest $request, 
        SystemMediaCategory $systemMediaCategory
    ){
        if (Config::getConfigValue('filesystem_disk')=='qiniu') {
            $auth = new Auth(env('QINIU_ACCESS_KEY'), env('QINIU_SECRET_KEY'));
            $bucketManager = new BucketManager($auth);
            $buckets = current($bucketManager->buckets());
            if (!$buckets) {
                return $this->error("QINIU_ACCESS_KEY或QINIU_SECRET_KEY错误！");
            }
            if (!in_array(env('QINIU_BUCKET'), $buckets)) {
                return $this->error(env('QINIU_BUCKET')."仓库不存在！");
            }
        }
        $files = $this->saveFiles($request);
        if (isset($files['file']['existed'])) {
            if ($files['file']['existed']) {
                return $this->error('文件 '.$files['file']['origin_filename'].' 已存在');
            } else {
                $media = $systemMediaCategory->media()->create($files['file']);
                return $this->created(SystemMediaResource::make($media));
            }
        } else {
            return $this->error('文件 '.$files['file']['origin_filename'].' 上传失败');
        }
    }

    /**
     * 获取分类下的所有文件
     *
     * @param SystemMediaCategory $systemMediaCategory
     * @param SystemMediaFilter $filter
     * @param SystemMediaRequest $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function systemMediaIndex(
        Request $request,
        SystemMediaCategory $systemMediaCategory, 
        SystemMediaFilter $filter
    ){
        if ($systemMediaCategory->parent_id == 0) {
            $categoryIdList = $systemMediaCategory->pluckId($systemMediaCategory->id);
            $request->merge(['category_id'=>$categoryIdList]);
        }
        $media = $systemMediaCategory->media()
            ->filter($filter)
            ->orderByDesc('id')
            ->paginate();

        return $this->ok(
            SystemMediaResource::collection($media)
        );
    }
}
